package com.birdy.controller;

import com.alibaba.fastjson.JSONObject;
import com.birdy.annotation.LogTimeUsed;
import com.birdy.con.AppConst;
import com.birdy.dto.Response;
import com.birdy.jwt.service.IEncryptService;
import com.birdy.service.IUserService;
import com.birdy.util.AppTokenHelper;
import com.birdy.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author birdy
 * @date 2022/5/3 2:31 PM
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IEncryptService encryptService;

    /**
     * 用户登录。将用户通过`wx.login()`拿到的code换取openid进行入库操作。
     * @param body code with userinfo
     * @return 登录成功返回openid -> base64 token，失败返回错误信息
     */
    @LogTimeUsed
    @PostMapping("login_with_info")
    public Response loginWithInfo(@RequestBody String body) {
        log.info("{}", body);
        JSONObject parseObject = JSONObject.parseObject(body);
        // 接口生效的条件是需要code以及userinfo
        if (parseObject.containsKey(AppConst.KEY_CODE)
                && parseObject.containsKey(AppConst.KEY_USER_INFO)) {
            String code = parseObject.getString(AppConst.KEY_CODE);
            UserInfo userInfo = parseObject.getObject(AppConst.KEY_USER_INFO, UserInfo.class);
            // code换取openid, session_key
            AppTokenHelper appTokenHelper = new AppTokenHelper();
            Response openIdAndSessionKey = appTokenHelper.getOpenIdAndSessionKey(code);
            // 接口调用失败
            if (openIdAndSessionKey.getRes() != Response.SUCCESS) {
                return openIdAndSessionKey;
            }
            String openid = (String) openIdAndSessionKey.getData().get(AppConst.KEY_OPENID);
            String userRegister = userService.checkUserInfoRegister(openid);
            // 注册过了
            if (userRegister != null) {
                int ret = userService.updateUserInfo(openid, userInfo);
                log.info("already register, ret:{}", ret);
            } else {
                int ret = userService.addUserInfo(openid, userInfo);
                log.info("a new boy, ret:{}", ret);
            }
            try {
                String token = encryptService.encryptBase64Password(openid);
                return Response.builder().res(Response.SUCCESS).msg("success")
                        .data(AppConst.KEY_TOKEN, token).build();
            } catch (Exception e) {
                log.error(e.getMessage());
                return Response.fail("encrypt error");
            }
        }
        return Response.fail("参数错误");
    }

    @GetMapping("/check")
    public Response checkUserLogin(@RequestParam String token) {
        try {
            // 解析token
            String openid = encryptService.decryptBase64Password(token);
            // 检查用户是否注册
            String userRegister = userService.checkUserInfoRegister(openid);
            if (userRegister != null) {
                return Response.success("success");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return Response.fail("fail");
    }

    @GetMapping("/hello")
    public Response sayHello() {
        return Response.success("hello");
    }
}
